<template>
  <div class="home-container">
    <!-- 导航栏 -->
    <Navbar logoText="易交易">
    </Navbar>

    <!-- 内容区域 - 添加顶部边距避免被固定导航栏遮挡 -->
    <div class="content-wrapper">
    <!-- 轮播图 -->
    <div class="carousel">
      <img src="../assets/banner.svg" alt="平台宣传图">
    </div>

    <!-- 商品分类 -->
    <section class="categories">
      <h2>商品分类</h2>
      <div class="category-list">
        <div v-for="category in categories" :key="category.category_id" class="category-item" @click="filterByCategory(category.category_id)">
          {{ category.name }}
        </div>
      </div>
    </section>

    <!-- 热门商品 -->
    <section class="hot-products">
      <h2>热门商品</h2>
      <div v-if="loading" class="loading-indicator">加载中...</div>
      <div v-else-if="products.length === 0" class="no-data">暂无商品数据</div>
      <div v-else class="product-list">
        <!-- 商品项将通过组件动态渲染 -->
        <div v-for="product in products" :key="product.product_id" class="product-item" @click="navigateToProduct(product.product_id)">
          <img :src="getProductImageUrl(product.image_url)" alt="商品图片">
          <h3>{{ product.title }}</h3>
          <p class="price">¥{{ product.price }}</p>
          <p class="location">未知位置</p>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="pagination" class="pagination-controls">
        <button @click="changePage(1)" :disabled="pagination.currentPage === 1">首页</button>
        <button @click="changePage(pagination.currentPage - 1)" :disabled="pagination.currentPage === 1">上一页</button>
        <span v-for="pageNum in pageRange" :key="pageNum" :class="{ 'active': pageNum === pagination.currentPage }" @click="changePage(pageNum)">{{ pageNum }}</span>
        <button @click="changePage(pagination.currentPage + 1)" :disabled="pagination.currentPage === pagination.totalPages">下一页</button>
        <button @click="changePage(pagination.totalPages)" :disabled="pagination.currentPage === pagination.totalPages">末页</button>
        <span class="page-info">共 {{ pagination.totalPages }} 页 / {{ pagination.totalItems }} 条</span>
      </div>
    </section>

    <!-- 页脚 -->
    <footer>
      <p>© 2023 易交易 - 校园二手交易平台</p>
    </footer>
    </div>
  </div>
</template>

<script setup lang="ts">
import Navbar from '../components/Navbar.vue';
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import moment from 'moment';

// 创建路由实例
const router = useRouter();

// 响应式变量
const categories = ref<Array<{ category_id: number; name: string; icon_url: string }>>([]);
const products = ref<Array<{ product_id: number; title: string; price: number; image_url: string }>>([]);
const loading = ref(true);
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const defaultProductImg = '/src/assets/product.svg';
const currentPage = ref(1);
const pageSize = ref(10);
const pagination = ref<{
  currentPage: number;
  pageSize: number;
  totalItems: number;
  totalPages: number;
} | null>(null);
const currentCategoryId = ref<number | null>(null);

/**
 * 获取商品图片URL
 * @param imageUrl 图片相对路径
 * @returns 完整的图片URL
 */
const getProductImageUrl = (imageUrl: string | null): string => {
  if (!imageUrl) return defaultProductImg;
  if (imageUrl.startsWith('http') || imageUrl.startsWith('data:')) return imageUrl;
  if (imageUrl.startsWith('/uploads/')) return API_BASE + imageUrl;
  return defaultProductImg;
};

/**
 * 获取所有商品分类
 */
const fetchCategories = async () => {
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 请求获取商品分类`);
    const response = await axios.get('/api/product/categories');
    categories.value = response.data.categories || [];
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 商品分类获取成功: ${categories.value.length} 个分类`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Home] 获取商品分类失败:`, err, err?.response?.data);
    alert('获取商品分类失败');
  }
};

/**
 * 获取热门商品
 */
const fetchHotProducts = async () => {
  try {
    loading.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 请求获取热门商品: 页码=${currentPage.value}, 每页数量=${pageSize.value}`);
    // 调用新的热门商品API
    const response = await axios.get('/api/product/hot', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    products.value = response.data.products || [];
    pagination.value = response.data.pagination || null;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 热门商品获取成功: ${products.value.length} 个商品`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Home] 获取热门商品失败:`, err, err?.response?.data);
    alert('获取商品数据失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 按分类筛选商品
 * @param categoryId 分类ID
 */
const filterByCategory = async (categoryId: number) => {
  try {
    currentCategoryId.value = categoryId;
    currentPage.value = 1; // 切换分类时重置到第一页
    loading.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 请求按分类筛选商品: categoryId=${categoryId}, 页码=${currentPage.value}, 每页数量=${pageSize.value}`);
    const response = await axios.get('/api/product/hot', {
      params: {
        categoryId,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    products.value = response.data.products || [];
    pagination.value = response.data.pagination || null;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 分类商品获取成功: ${products.value.length} 个商品`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Home] 按分类筛选商品失败:`, err, err?.response?.data);
    alert('筛选商品失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 切换页码
 * @param pageNum 目标页码
 */
const changePage = (pageNum: number) => {
  if (pageNum < 1 || (pagination.value && pageNum > pagination.value.totalPages)) {
    return;
  }
  currentPage.value = pageNum;
  if (currentCategoryId.value) {
    filterByCategory(currentCategoryId.value);
  } else {
    fetchHotProducts();
  }
};

/**
 * 生成页码范围
 */
const pageRange = computed(() => {
  if (!pagination.value) return [];
  const { currentPage, totalPages } = pagination.value;
  const range = [];
  const showPages = 5; // 显示的页码数量

  // 计算起始页码
  let startPage = Math.max(1, currentPage - Math.floor(showPages / 2));
  // 调整结束页码
  let endPage = startPage + showPages - 1;
  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - showPages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 导航到商品详情页
 * @param productId 商品ID
 */
const navigateToProduct = (productId: number) => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 导航到商品详情: productId=${productId}`);
  router.push(`/product/${productId}`);
};

// 组件挂载时获取数据
onMounted(() => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Home] 组件已挂载，开始获取数据`);
  fetchCategories();
  fetchHotProducts();
});
</script>

<style scoped>
/* 主页样式 */
.home-container {
  max-width: 100vw;
  margin: 0 auto;
  padding: 0 2vw;
  background-color: #ffffff;
  box-sizing: border-box;
}

.content-wrapper {
  padding-top: 80px; /* 为固定导航栏预留空间 */
}


.home-container .carousel img {
  width: 100%;
  height: clamp(220px, 30vh, 400px);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-medium);
  transition: var(--transition-default);
  object-fit: cover;
  margin: 20px 0;
}

.home-container .categories {
  margin: 30px 0;
}

.category-list {
  display: flex;
  gap: 2vw;
}

.home-container .category-item {
  flex: 1;
  text-align: center;
  padding: 20px;
  background: var(--primary-color);
  border-radius: var(--border-radius-md);
  transition: var(--transition-default);
  cursor: pointer;
  font-weight: 550;
  font-stretch: semi-expanded;

  &:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-medium);
    background-color: #d1e7fd;
  }
}

.home-container .hot-products {
  margin: 30px 0;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 2vw;
  padding: 0 1vw;
}

.home-container .product-item {
  background: white;
  border-radius: var(--border-radius-md);
  padding: 15px;
  box-shadow: var(--shadow-light);
  transition: var(--transition-default);
  cursor: pointer;

  h3 {
    margin: 10px 0;
    font-weight: 550;
    font-stretch: semi-expanded;
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-medium);
  }
}

/* 添加商品图片尺寸限制 */
.home-container .product-item img {
  width: 100%;
  height: clamp(150px, 20vh, 200px);
  object-fit: cover;
  border-radius: var(--border-radius-sm);
}

/* 其他样式保持不变 */

/* 分页控件样式 */
.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  gap: 10px;
}

.pagination-controls button {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: var(--border-radius-sm);
  cursor: pointer;
  transition: var(--transition-default);

  &:hover:not(:disabled) {
    background-color: #e0e0e0;
  }

  &:disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }
}

.pagination-controls span {
  padding: 6px 10px;
  cursor: pointer;
  border-radius: var(--border-radius-sm);

  &.active {
    background-color: var(--primary-color);
    font-weight: bold;
  }

  &:not(.active):hover {
    background-color: #f0f0f0;
  }
}

.pagination-controls .page-info {
  margin-left: 15px;
  cursor: default;
}

/* 加载中和无数据样式 */
.loading-indicator,
.no-data {
  text-align: center;
  padding: 50px 0;
  color: #666;
}
</style>